<?php

use think\Db;
use jiguang\JSMS;
use jiguang\Sign;
//根据地址获取经纬度
function getPosition($address)
{
    $ak='WM5BZ-GSX6X-O644O-7LUGN-DAW4V-GCBVD';
    $url="http://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key={$ak}";
    $json=file_get_contents($url);
    $data=json_decode($json,TRUE);
    return $data;
}
/*
    * 生成随机数
    */
function randomkeys($length)
{
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyz   
               ABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    $key = 'lv_';
    for($i=0;$i<$length;$i++)
    {
        $key .= $pattern{mt_rand(0,35)};    //生成php随机数
    }
    return $key;
}

function getTree($list,$pid=0,$level=0) {
    static $tree = array();
    foreach($list as $row) {
        if($row['pid']==$pid) {
            $row['level'] = $level;
            $tree[] = $row;
            getTree($list, $row['id'], $level + 1);
        }
    }
    return $tree;
}

/**
 * 设置，获取指定的全局配置
 */
function lvConf($key,$v = ''){
    if(is_null($v)){
        if(array_key_exists('LVCONF',$GLOBALS) && array_key_exists($key,$GLOBALS['LVCONF'])){
            unset($GLOBALS['LVCONF'][$key]);
        }
    }else if($v === ''){
        if(array_key_exists('LVCONF',$GLOBALS)){
            $conf = $GLOBALS['LVCONF'];
            $ks = explode(".",$key);
            for($i=0,$k=count($ks);$i<$k;$i++){
                if(array_key_exists($ks[$i],$conf)){
                    $conf = $conf[$ks[$i]];
                }else{
                    return null;
                }
            }
            return $conf;
        }
    }else{
        return $GLOBALS['LVCONF'][$key] = $v;
    }
    return null;
}

/**
 * 订单状态
 */
function  lvOrderStatus($v)
{
    switch ($v) {
        case 0:
            return '待付款';
        case 1:
            return '未出行';
        case 2:
            return '交易关闭';
        case 3:
            return '待评价';
        case 4:
            return '完成';
        case 5:
            return '已取消';
        case 6:
            return '待确认';
    }
}

/**
 * 获取支付方式
 */
function lvPayType($v){
    switch ($v) {
        case 1:
            return '支付宝';
        case 2:
            return '微信';
    }
}

/*
 * 根据地址获取经纬度
 */
function getDoc($address)
{

    $url='http://restapi.amap.com/v3/geocode/geo?address='.$address.'&key=358e193808b3b90caecc22bb5dfd23b8';
    if($result=file_get_contents($url)) {
        $result = json_decode($result, true);
        //判断是否成功
        if (!empty($result['count'])) {
            return explode(',', $result['geocodes']['0']['location']);

        } else {
            return false;
        }
    }
}
/** 根据经纬度计算距离
 * @param $lat1
 * @param $lng1
 * @param $lat2
 * @param $lng2
 * @return int
 */
function getDistance($lat1, $lng1, $lat2, $lng2){

    //将角度转为狐度

    $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度

    $radLat2=deg2rad($lat2);

    $radLng1=deg2rad($lng1);

    $radLng2=deg2rad($lng2);

    $a=$radLat1-$radLat2;

    $b=$radLng1-$radLng2;

    $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;

    return round($s,2);

}

/**
 * [makeOrderSn 生成订单号]
 * @Author   kendy
 * @DateTime 2019-11-04T15:21:51+0800
 * @return   [type]                   [description]
 */
 function makeOrderSn()
{
   return  date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
 
/**
 * [send_user_message 给用户发送站内消息]
 * @Author   kendy
 * @DateTime 2019-11-04T15:22:21+0800
 * @param    [type]                   $scene         [sense为config里的值，]
 * @param    [type]                   $type          [订单类型]
 * @param    [type]                   $receiveUserId [接收的用户id]
 * @param    string                   $orderSn       [订单编号]
 * @param    string                   $name          [名称]
 * @return   [type]                                  [description]
 */
function send_user_message($scene,$msg_type,$receiveUserId,$orderSn='',$name='',$oid='',$type)
{ 
    $smsParams = array(
        1 => "{\"order_sn\":\"$orderSn\",\"name\":\"$name\"}"
    );
    $paramsArr = json_decode($smsParams[1]);
    // 消息提醒的主体内容
    $content = config('config.send_user_message')[$scene][1];
    // 消息提醒的标题
    $title = config('config.send_user_message')[$scene][0];
    foreach ($paramsArr as $k => $v) {
        $content = str_replace('${' . $k . '}', $v, $content);
        $title = str_replace('${' . $k . '}', $v, $title);
    }  
    $mess['msg_type'] = $msg_type;
    $mess['receive_user_id'] = $receiveUserId;
    $mess['msg_title'] = $title;
    $mess['create_time'] = date('Y-m-d H:i:s',time());
    $mess['msg_content'] =  $content;
    $mess['oid'] =  $oid;
    $mess['type'] = $type;
    return Db::name('message')->insertGetId($mess); 
 
}

function time_ago($posttime){
    //当前时间的时间戳
    $nowtimes = strtotime(date('Y-m-d H:i:s'),time());
    //之前时间参数的时间戳
    $posttimes = strtotime($posttime);

    //相差时间戳
    $counttime = $nowtimes - $posttimes;

    //进行时间转换
    if($counttime<=60){

        return '刚刚';

    }else if($counttime>60 && $counttime<3600){

        return intval(($counttime/60)).'分钟前';

    }else if($counttime>=3600 && $counttime<3600*24){

        return intval(($counttime/3600)).'小时前';

    }else if($counttime>=3600*24 && $counttime<3600*24*2){

        return '昨天';

    }else if($counttime>=3600*24*2 && $counttime<3600*24*3){

        return '前天';

    }else if($counttime>=3600*24*3 && $counttime<=3600*24*30){

        return intval(($counttime/(3600*24))).'天前';

    }else{

        return $posttime;

    }

}

/**
 * [format_date 计算的时间]
 * @Author   kendy
 * @DateTime 2019-12-05T13:37:22+0800
 * @param    [type]                   $time [description]
 * @return   [type]                         [description]
 */
 function format_date($time){
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            } 

        }
}

//极光模板短信发送
function sendJsmsMessage($user_id,$temp_id,$temp_para,$time = null,$sign_id = null){

    $app_key = config('JSMS.app_key');

    $master_secret = config('JSMS.master_secret');

    //查询客户电话
    $user = Db::name('user')->field("phone")->where("uid",$user_id)->find();
    if($user){
        $tel =$user['phone'];
    }else{
        $tel = $user_id;
    }

    $client = new JSMS($app_key, $master_secret,[ 'disable_ssl' => true ]);

    $res = $client->sendMessage($tel, $temp_id,$temp_para, $time, $sign_id);

    return $res;
}

//极光验证码短信发送
function sendJsmsCode($mobile,$sign_id,$temp_id = 1){


    $app_key = config('JSMS.app_key');

    $master_secret = config('JSMS.master_secret');

    $client = new JSMS($app_key, $master_secret, [ 'disable_ssl' => true ]);

    $response = $client->sendCode($mobile, $temp_id,$sign_id);

    return $response;
}

//极光验证码验证
function checkJsmsCode($msg_id,$code){

    $app_key = config('JSMS.app_key');

    $master_secret = config('JSMS.master_secret');

    $client = new JSMS($app_key, $master_secret,[ 'disable_ssl' => true ]);

    $response = $client->checkCode($msg_id, $code);

    return $response;
}

/**
 * [getRandNumber 生成不重复的随机数字，可自定义长度]
 * @Author   kendy
 * @DateTime 2019-12-10T14:38:52+0800
 * @param    integer                  $start  [需要生成的数字开始范围]
 * @param    integer                  $end    [结束范围]
 * @param    integer                  $length [需要生成的随机数个数]
 * @return   [type]                           [生成的随机数]
 */
function getRandNumber($start=0,$end=9,$length=8){
    //初始化变量为0
    $connt = 0;
    //创建一个新数组
    $temp = array();
    while($connt < $length){
        //在一定的范围内随机生成一个数放入数组中
        $temp[] = mt_rand($start,$end); 
        $data = array_unique($temp); 
       //去除数组中的重复值用了 “翻翻法”，就是用array_flip()把数组的key和value交换两次，
       //比array_unique()快的多
       //
       $connt = count($data); 
    } 
    //为数组赋予新的键名
    shuffle($data);
    //数组转字符串
    $str = implode(",", $data);
    //替换掉都好
    $number = str_replace(",", '', $str);
    return $number;
}
/**
 * [makeCardPassword 随机生成不重复的8位卡密]
 * @Author   kendy
 * @DateTime 2019-12-10T14:58:11+0800
 * @return   [type]                   [description]
 */
function makeCardPassword() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    //rand() 随机返回随机整数  
    //strtoupper() 把所有字符串传转换为大写
    //dechex() 把十进制转换为十六进制： 
    //substr(string,start,length) 函数返回字符串的一部分。 string 规定要返回其中一部分的字符串
    //microtime() 返回当前 Unix 时间戳的微秒数：
    $rand  = $code[rand(0,25)].strtoupper(dechex(date('m'))).date('d').substr(time(),-5)
    .substr(microtime(),2,5)
    .sprintf('%02d',rand(0,99));
    for(

        $a = md5($rand ,true),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV', 
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++ 
    ); 
        return $d;
}


  /**
    * [addWaterByField 添加单个字段水印]
    * @Author   kendy
    * @DateTime 2020-01-21T09:21:05+0800
    * @param    [type]                   $val [description]
    */
    function addWaterByField($val){
        if(!empty($val))
            return $val.'-lv';
        else
            return $val;

    }  